package com.zy.web.service.impl;

import com.zy.common.core.domain.model.LoginUser;
import com.zy.common.helper.LoginHelper;
import com.zy.common.utils.sql.StringUtils;
import com.zy.common.core.page.TableDataInfo;
import com.zy.common.core.domain.PageQuery;
import com.zy.web.domain.bo.ZyCompetitionBo;
import com.zy.web.domain.vo.ZyCompetitionVo;
import com.zy.web.mapper.ZyUserMapper;
import com.zy.web.repository.ZyCompetitionRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import com.zy.web.domain.ZyCompetition;
import com.zy.web.service.IZyCompetitionService;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 竞赛项目Service业务层处理
 *
 * @author zy
 * @date 2024-02-25
 */
@RequiredArgsConstructor
@Service
public class ZyCompetitionServiceImpl implements IZyCompetitionService {

    private final ZyCompetitionRepository repository;
    private final ZyUserMapper userMapper;

    /**
     * 查询竞赛项目
     */
    @Override
    public ZyCompetitionVo queryById(String id) {
        return repository.findById(id).map(v -> com.zy.common.utils.BeanCopyUtils.copy(v, ZyCompetitionVo.class)).orElse(null);
    }

    /**
     * 查询竞赛项目列表
     */
    @Override
    public TableDataInfo<ZyCompetitionVo> queryPageList(ZyCompetitionBo bo, PageQuery pageQuery) {
        Page<ZyCompetition> result = repository.findAll(getSpecification(bo), pageQuery.pageable());
        return TableDataInfo.build(result, ZyCompetitionVo.class);
    }

    /**
     * 查询当前用户的竞赛项目列表
     */
    @Override
    public TableDataInfo<ZyCompetitionVo> queryPageListCurr(ZyCompetitionBo bo, PageQuery pageQuery) {
        Page<ZyCompetition> result = repository.findAll(getSpecificationCurr(bo), pageQuery.pageable());
        return TableDataInfo.build(result, ZyCompetitionVo.class);
    }


    private Specification<ZyCompetition> getSpecificationCurr(ZyCompetitionBo bo) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getId())) {
                predicates.add(cb.equal(root.get("id"), bo.getId()));
            }
            if (bo.getCreateBy() != null) {
                predicates.add(cb.equal(root.get("createBy"), bo.getCreateBy()));
            }
            if (bo.getCreateTime() != null) {
                predicates.add(cb.equal(root.get("createTime"), bo.getCreateTime()));
            }
            if (bo.getUpdateBy() != null) {
                predicates.add(cb.equal(root.get("updateBy"), bo.getUpdateBy()));
            }
            if (bo.getUpdateTime() != null) {
                predicates.add(cb.equal(root.get("updateTime"), bo.getUpdateTime()));
            }
            if (StringUtils.isNotBlank(bo.getCp())) {
                predicates.add(cb.equal(root.get("cp"), bo.getCp()));
            }
            if (bo.getCprs() != null) {
                predicates.add(cb.equal(root.get("cprs"), bo.getCprs()));
            }

            if (StringUtils.isNotBlank(bo.getDd())) {
                predicates.add(cb.equal(root.get("dd"), bo.getDd()));
            }
            if (StringUtils.isNotBlank(bo.getRyyq())) {
                predicates.add(cb.equal(root.get("ryyq"), bo.getRyyq()));
            }
            if (bo.getSj() != null) {
                predicates.add(cb.equal(root.get("sj"), bo.getSj()));
            }
            if (StringUtils.isNotBlank(bo.getWz())) {
                predicates.add(cb.equal(root.get("wz"), bo.getWz()));
            }
            if (StringUtils.isNotBlank(bo.getXmlx())) {
                predicates.add(cb.equal(root.get("xmlx"), bo.getXmlx()));
            }
            if (StringUtils.isNotBlank(bo.getXmmc())) {
                predicates.add(cb.equal(root.get("xmmc"), bo.getXmmc()));
            }
            if (StringUtils.isNotBlank(bo.getYhm())) {
                predicates.add(cb.equal(root.get("yhm"), bo.getYhm()));
            }
            if (bo.getZdrs() != null) {
                predicates.add(cb.equal(root.get("zdrs"), bo.getZdrs()));
            }
            if (StringUtils.isNotBlank(bo.getZyz())) {
                predicates.add(cb.equal(root.get("zyz"), bo.getZyz()));
            }
            if (bo.getZyzrs() != null) {
                predicates.add(cb.equal(root.get("zyzrs"), bo.getZyzrs()));
            }

            //查询所有的id和csz
            List<ZyCompetitionRepository.IdAndCsz> allIdAndCsz = repository.findAllIdAndCsz();
            List<String> ids = new ArrayList<>(); //
            for (ZyCompetitionRepository.IdAndCsz idAndCsz : allIdAndCsz) {
                String csz = idAndCsz.getCsz();
                if (csz == null) continue; //当前项目没人参加
                List<String> cszList = Arrays.asList(csz.split(","));
                if (cszList.contains(LoginHelper.getLoginUser().getUsername())) { //项目中的人员包含当前用户
                    ids.add(idAndCsz.getId());
                }
            }
            predicates.add(root.get("id").in(ids));

            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 查询竞赛项目列表
     */
    @Override
    public List<ZyCompetitionVo> queryList(ZyCompetitionBo bo) {
        return repository.findAll(getSpecification(bo)).stream()
                .map(v -> com.zy.common.utils.BeanCopyUtils.copy(v, ZyCompetitionVo.class))
                .collect(Collectors.toList());
    }

    private Specification<ZyCompetition> getSpecification(ZyCompetitionBo bo) {
        return (root, query, cb) -> {
            Map<String, Object> params = bo.getParams();
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getId())) {
                predicates.add(cb.equal(root.get("id"), bo.getId()));
            }
            if (bo.getCreateBy() != null) {
                predicates.add(cb.equal(root.get("createBy"), bo.getCreateBy()));
            }
            if (bo.getCreateTime() != null) {
                predicates.add(cb.equal(root.get("createTime"), bo.getCreateTime()));
            }
            if (bo.getUpdateBy() != null) {
                predicates.add(cb.equal(root.get("updateBy"), bo.getUpdateBy()));
            }
            if (bo.getUpdateTime() != null) {
                predicates.add(cb.equal(root.get("updateTime"), bo.getUpdateTime()));
            }
            if (StringUtils.isNotBlank(bo.getCp())) {
                predicates.add(cb.equal(root.get("cp"), bo.getCp()));
            }
            if (bo.getCprs() != null) {
                predicates.add(cb.equal(root.get("cprs"), bo.getCprs()));
            }

            if (StringUtils.isNotBlank(bo.getDd())) {
                predicates.add(cb.equal(root.get("dd"), bo.getDd()));
            }
            if (StringUtils.isNotBlank(bo.getRyyq())) {
                predicates.add(cb.equal(root.get("ryyq"), bo.getRyyq()));
            }
            if (bo.getSj() != null) {
                predicates.add(cb.equal(root.get("sj"), bo.getSj()));
            }
            if (StringUtils.isNotBlank(bo.getWz())) {
                predicates.add(cb.equal(root.get("wz"), bo.getWz()));
            }
            if (StringUtils.isNotBlank(bo.getXmlx())) {
                predicates.add(cb.equal(root.get("xmlx"), bo.getXmlx()));
            }
            if (StringUtils.isNotBlank(bo.getXmmc())) {
                predicates.add(cb.equal(root.get("xmmc"), bo.getXmmc()));
            }
            if (StringUtils.isNotBlank(bo.getYhm())) {
                predicates.add(cb.equal(root.get("yhm"), bo.getYhm()));
            }
            if (bo.getZdrs() != null) {
                predicates.add(cb.equal(root.get("zdrs"), bo.getZdrs()));
            }
            if (StringUtils.isNotBlank(bo.getZyz())) {
                predicates.add(cb.equal(root.get("zyz"), bo.getZyz()));
            }
            if (bo.getZyzrs() != null) {
                predicates.add(cb.equal(root.get("zyzrs"), bo.getZyzrs()));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 新增竞赛项目
     */
    @Override
    public Boolean insertByBo(ZyCompetitionBo bo) {
        ZyCompetition add = com.zy.common.utils.BeanCopyUtils.copy(bo, ZyCompetition.class);
        validEntityBeforeSave(add);
        repository.saveAndFlush(add);
        bo.setId(add.getId());
        return true;
    }

    /**
     * 修改竞赛项目
     */
    @Override
    public Boolean updateByBo(ZyCompetitionBo bo) {
        ZyCompetition update = com.zy.common.utils.BeanCopyUtils.copy(bo, ZyCompetition.class);
        validEntityBeforeSave(update);
        return repository.save(update) != null;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZyCompetition entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除竞赛项目
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        repository.deleteAllById(ids);
        return true;
    }

}
